const express = require("express");
const router = express.Router();
const Comment = require("../controllers/commentController");
const commentObj = new Comment();
const Jwt = require("../common/jwt");

// 添加评论
// 请求地址：http://localhost:3001/api/comment/add
// 参数：article_id, content, parent_id(可选，回复评论时使用), token
router.post("/add", async (req, res) => {
  let { article_id, content, parent_id } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token || !article_id || !content) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    const user_id = result.info.data;
    await commentObj.add(article_id, user_id, content, parent_id || 0, 'published')
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 获取文章评论列表
// 请求地址：http://localhost:3001/api/comment/list
// 参数：article_id, page_num, page_size
router.post("/list", async (req, res) => {
  let { article_id, page_num, page_size } = req.body;

  if (!article_id) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数article_id"
    });
    return;
  }

  // 默认分页参数
  page_num = page_num || 1;
  page_size = page_size || 10;

  await commentObj.getList(article_id, page_num, page_size)
    .then(
      result => {
        res.status(200).json(result);
      },
      err => {
        res.status(500).json(err);
      }
    );
});

// 删除评论
// 请求地址：http://localhost:3001/api/comment/delete
// 参数：id, token
router.post("/delete", async (req, res) => {
  let { id } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token || !id) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    const user_id = result.info.data;
    await commentObj.delete(id, user_id)
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 获取用户的所有评论
// 请求地址：http://localhost:3001/api/comment/user
// 参数：page_num, page_size, token
router.post("/user", async (req, res) => {
  let { page_num, page_size } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token) {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    const user_id = result.info.data;
    page_num = page_num || 1;
    page_size = page_size || 10;

    await commentObj.getUserComments(user_id, page_num, page_size)
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 管理员获取所有评论列表
// 请求地址：http://localhost:3001/api/comment/admin/list
// 参数：page_num, page_size, keyword(可选), token
router.post("/admin/list", async (req, res) => {
  let { page_num, page_size, keyword } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token) {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    page_num = page_num || 1;
    page_size = page_size || 10;

    await commentObj.getAllComments(page_num, page_size, keyword)
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 管理员搜索评论
// 请求地址：http://localhost:3001/api/comment/admin/search
// 参数：keyword, token
router.post("/admin/search", async (req, res) => {
  let { keyword } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token) {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
    return;
  }

  if (!keyword || !keyword.trim()) {
    res.status(400).json({
      code: -1,
      msg: "搜索关键词不能为空"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    await commentObj.getAllComments(1, 1000, keyword)
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 管理员隐藏评论
// 请求地址：http://localhost:3001/api/comment/admin/hide
// 参数：id, token
router.post("/admin/hide", async (req, res) => {
  let { id } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token || !id) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数"
    });
    return;
  }

  // 校验token
  let jwtResult = new Jwt(token).verifyToken();
  if (jwtResult.code == 200) {
    const userId = jwtResult.info.data;
    const db = require("../common/db/index");

    try {
      // 验证是否为管理员
      const roleSql = 'SELECT role FROM pre_user WHERE id = ?';
      const roleResult = await db.query(roleSql, [userId]);
      if (roleResult.length == 0 || roleResult[0].role != '1') {
        res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以隐藏评论" });
        return;
      }

      // 获取操作者用户名和评论信息
      const userInfoSql = 'SELECT username FROM pre_user WHERE id = ?';
      const commentInfoSql = 'SELECT c.content, u.username as comment_author FROM pre_comment c LEFT JOIN pre_user u ON c.user_id = u.id WHERE c.id = ?';
      const [operatorInfo, commentInfo] = await Promise.all([
        db.query(userInfoSql, [userId]),
        db.query(commentInfoSql, [id])
      ]);

      await commentObj.hideComment(id)
        .then(
          async result => {
            // 记录操作日志
            const OperationLog = require("../controllers/operationLogController");
            const operationLogObj = new OperationLog();
            const operatorName = operatorInfo[0]?.username || '未知用户';
            const commentContent = commentInfo[0]?.content || '';
            const commentAuthor = commentInfo[0]?.comment_author || '未知用户';
            const contentPreview = commentContent.length > 30 ? commentContent.substring(0, 30) + '...' : commentContent;
            await operationLogObj.add(
              userId,
              operatorName,
              '隐藏评论',
              `隐藏评论（ID: ${id}），作者：${commentAuthor}，内容：${contentPreview}`
            ).catch(err => console.error('记录操作日志失败:', err));

            res.status(200).json(result);
          },
          err => {
            res.status(500).json(err);
          }
        );
    } catch (error) {
      res.status(500).json({ code: -1, msg: "隐藏评论失败", error: error.message });
    }
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 管理员恢复评论
// 请求地址：http://localhost:3001/api/comment/admin/restore
// 参数：id, token
router.post("/admin/restore", async (req, res) => {
  let { id } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token || !id) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    await commentObj.restoreComment(id)
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 管理员删除评论
// 请求地址：http://localhost:3001/api/comment/admin/delete
// 参数：id, token
router.post("/admin/delete", async (req, res) => {
  let { id } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token || !id) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数"
    });
    return;
  }

  // 校验token
  let jwtResult = new Jwt(token).verifyToken();
  if (jwtResult.code == 200) {
    const userId = jwtResult.info.data;
    const db = require("../common/db/index");

    try {
      // 验证是否为管理员
      const roleSql = 'SELECT role FROM pre_user WHERE id = ?';
      const roleResult = await db.query(roleSql, [userId]);
      if (roleResult.length == 0 || roleResult[0].role != '1') {
        res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以删除评论" });
        return;
      }

      // 获取操作者用户名和评论信息
      const userInfoSql = 'SELECT username FROM pre_user WHERE id = ?';
      const commentInfoSql = 'SELECT c.content, u.username as comment_author FROM pre_comment c LEFT JOIN pre_user u ON c.user_id = u.id WHERE c.id = ?';
      const [operatorInfo, commentInfo] = await Promise.all([
        db.query(userInfoSql, [userId]),
        db.query(commentInfoSql, [id])
      ]);

      await commentObj.adminDelete(id)
        .then(
          async result => {
            // 记录操作日志
            const OperationLog = require("../controllers/operationLogController");
            const operationLogObj = new OperationLog();
            const operatorName = operatorInfo[0]?.username || '未知用户';
            const commentContent = commentInfo[0]?.content || '';
            const commentAuthor = commentInfo[0]?.comment_author || '未知用户';
            const contentPreview = commentContent.length > 30 ? commentContent.substring(0, 30) + '...' : commentContent;
            await operationLogObj.add(
              userId,
              operatorName,
              '删除评论',
              `删除评论（ID: ${id}），作者：${commentAuthor}，内容：${contentPreview}`
            ).catch(err => console.error('记录操作日志失败:', err));

            res.status(200).json(result);
          },
          err => {
            res.status(500).json(err);
          }
        );
    } catch (error) {
      res.status(500).json({ code: -1, msg: "删除评论失败", error: error.message });
    }
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

module.exports = router;

